<template>
  <div class="in-wrap">
    <!-- 公共头引入 -->
    <!-- <my-nav v-show="isGoToHome"></my-nav> -->
    <main-nav v-show="isGoToHome"></main-nav>
    <!-- /公共头引入 -->

    <nuxt :style="styleObject" />
    <!-- 公共底引入 -->

    <!-- /公共底引入 -->
    <div class="feedback">
      <div class="one" @click="feedbackup = true">
        <svg-icon icon-class="feedback" class="feedbackicon" />
        <div style="font-size: 0.729vw;">反馈</div>
        <el-dialog :append-to-body="true" title="提示" :visible.sync="feedbackup" width="35%" :before-close="handleClose"
          center>
          <el-form ref="form" :model="form" :rules="rules" label-position="left" class="form-vertical">
            <el-form-item label="反馈内容" prop="content">
              <el-input type="textarea" v-model="form.content"></el-input>
            </el-form-item>
            <div style="margin-bottom: 10px">上传文件</div>
            <el-upload name="file" class="upload-demo" drag
              action="http://42.194.233.38:8222/minioservice/minio-upload/upload" :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload" :data="uploadData" :headers="headers" multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
            <el-form-item label="反馈类型" style="margin-top: 10px" prop="typeId">
              <el-select v-model="form.typeId" placeholder="请选择反馈类型" style="type">
                <el-option v-for="(item, index) in feddBackType" :label="item.value" :value="item.id"
                  :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input type="text" v-model="form.phone"></el-input>
            </el-form-item>
            <el-form-item>
              <center>
                <el-button type="primary" @click="onSubmit" :loading="submitFeddBackLoading">提交</el-button>
                <el-button @click="feedbackup = false">取 消</el-button>
              </center>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div class="two" type="text" @click="centerDialogVisible = true">
        <svg-icon icon-class="callme" class="contact" />
        <div class="callMe">联系我们</div>
        <el-dialog :append-to-body="true" title="提示" :visible.sync="centerDialogVisible" width="35%" center>
          <span class="tel">软件协会会长联系方式:17819212602</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
// 自动重新连接ws插件
import { queryById } from "@/api/user.js";
import ReconnectingWebSocket from "reconnecting-websocket";
import * as commonUtil from "@/utils/commonUtil";
import MainNav from "@/components/mainPage/mainNav.vue";
import { init } from "@/plugins/permission";
import Cookies from "js-cookie";
import { addFeedBack, getAllFeedBackInfo } from "@/api/cms/cms.js";

export default {
  components: {
    MainNav,
  },
  computed: {
    styleObject() {
      return { margin: "0 auto", width: "100%" };
    },
  },
  data() {
    return {
      isHello: false, // 是否已经打招呼标识
      isGoToHome: false, //是否为首页
      feedbackup: false, //是否点击反馈,弹出弹窗的控制
      submitFeddBackLoading: false, //提交反馈loading
      centerDialogVisible: false, //联系我们
      uploadData: { bucketName: "feedback" }, //上传图片
      feddBackType: [], //反馈类型
      headers: {},
      form: {
        clientId: 0,
        clientName: "pc端",
        content: "",
        image: "",
        phone: "",
        name: "",
        typeId: "",
        typeName: "",
        userId: "",
      },
      rules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" },
          { min: 3, message: "内容至少需要三个字符", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        typeId: [
          { required: true, message: "类型ID不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.setHeaders();

    if (this.$route.path !== "/") {
      this.isGoToHome = true;
    } else {
      this.isGoToHome = false;
    }
  },
  async mounted() {
    init();
    this.queryAllFeedBackInfo();
    await this.initWs();
    // 判断微信内置浏览器
    if (navigator.userAgent.match(/(MicroMessenger)/i)) {
      const percentageOn1 = (window.screen.width / 1920) * 120;
      document.body.style.zoom = percentageOn1 + "%";
    }
    // 其他代码...
  },
  watch: {
    // 使用字符串路径监听 $route 对象的变化
    "$route.path": function (newPath, oldPath) {
      if (newPath !== "/") {
        this.isGoToHome = true;
      } else {
        this.isGoToHome = false;
      }
    },
  },
  methods: {
    // 设置 headers
    setHeaders() {
      this.headers = {
        token: Cookies.get("token"),
      };
    },
    //获取反馈类型
    queryAllFeedBackInfo() {
      getAllFeedBackInfo().then((res) => {
        if (res.code === 20000) {
          this.feddBackType = res.data.feedBackTypeEnums;
        }
      });
    },
    //根据反馈类型id去查找反馈类型名称，并赋值给表单
    queryTypeName(id) {
      let typeName = "";
      this.feddBackType.forEach((item) => {
        if (item.id === id) {
          typeName = item.value;
        }
      });
      this.form.typeName = typeName;
    },
    //提交反馈表单
    onSubmit() {
      this.submitFeddBackLoading = true;
      //根据id去找反馈类型名称
      this.queryTypeName(this.form.typeId);
      this.form.userId = this.$store.state.userInfo.id;
      this.form.name = this.$store.state.userInfo.nickname;
      //判断数据是否正确
      this.$refs.form.validate((valid) => {
        if (valid) {
          addFeedBack(this.form).then((res) => {
            if (res.code === 20000) {
              this.$message.success(res.message);
              this.feedbackup = false;
              this.submitFeddBackLoading = false;
            } else {
              this.$message.error(res.message);
              this.feedbackup = false;
              this.submitFeddBackLoading = false;
            }
          });
        } else {
          this.$message.error("请输入正确的数据");
          this.submitFeddBackLoading = false;
          return false;
        }
      });
    },
    // 反馈栏
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => { });
    },
    //上传图片
    handleAvatarSuccess(response) {
      // 假设上传成功后，服务器返回图片的URL
      if (response.success) {
        this.form.image = response.data.url;
      } else {
        this.$message.error("上传失败");
      }
    },
    beforeAvatarUpload(file) {
      // 可以在这里添加文件类型和大小的校验
      if (file.type !== "image/jpeg" && file.type !== "image/png") {
        this.$message.error("图片必须是jpg或png格式!");
        return false;
      } else if (file.size / 1024 / 1024 > 2) {
        this.$message.error("图片必须小于2MB!");
        return false;
      }
      return true;
    },

    openHello(title, message) {
      this.$notify.success({
        title: title,
        message: message,
        dangerouslyUseHTMLString: true,
        showClose: false,
        position: "bottom-right",
      });
    },
    openNotice(title, message) {
      this.$notify({
        title: title,
        message: message,
        dangerouslyUseHTMLString: true,
        showClose: false,
        offset: 100,
        iconClass: "el-icon-message-solid",
      });
    },
    formatDate(time) {
      let date = new Date(time); // 将毫秒数转换为日期对象
      // 获取日期部分
      const hour = date.getHours();
      const minute = date.getMinutes();
      const second = date.getSeconds();
      return `${hour}:${minute}:${second}`; // 输出 "13:11:13"格式
    },
    async initWs() {
      let token = commonUtil.getStore("token");
      const url =
        process.env.WS_URL + "/websocketservice/" + (token ? token : "-1");
      let webSocket = new ReconnectingWebSocket(url);

      // 连接成功
      webSocket.onopen = function () {
        // console.log("连接成功");
      };

      // 监听消息
      webSocket.onmessage = async (msg) => {
        // console.log("ws收到消息", msg.data);
        if (!isNaN(new Date(msg.data.substr(1, msg.data.length - 2)).getTime())) {
          this.$store.commit('updateNowTime', msg.data.substr(1, msg.data.length - 2))
          return;
        }
        let data = JSON.parse(msg.data);
        let message = "你好呀";
        let title = "通知";
        let comment = "内容";
        let active = "阅读";
        let type = data.type;
        let commentType = data.commentType;
        let gmtCreate = data.gmtCreate;
        let userId = data.userId; // 用户ID
        let nickname = data.nickname;
        if (nickname != "同学") {
          nickname = data.nickname + "同学";
        }
        try {
          if (userId != null) {
            // 异步获取用户信息
            let res = await queryById(userId);
            nickname = res.data.data.user.nickname;
          }
        } catch (error) {
          console.error("获取用户信息失败：", error);
        }

        let commentId = data.commentId; // 可链接帖子详情
        let formattedDate = this.formatDate(gmtCreate); // 格式化日期
        switch (type) {
          case 0:
            title = "系统通知";
            if (!this.isHello) {
              // 系统通知
              this.isHello = true;
              let hour = new Date().getHours();
              let time =
                hour >= 6 && hour < 12
                  ? "早上好呀"
                  : hour >= 12 && hour < 18
                    ? "下午好呀"
                    : hour >= 18 || hour <= 0
                      ? "晚上好呀"
                      : "天色有些晚咯,早点睡噢";
              message = `<h3>${time}, ${nickname}</h3>欢迎进入软件协会官网</br>当前在线人数:<span style="color:red">${data.count}</span>人`;
              this.openHello(title, message);
            } else {
              // 处理其它系统通知
            }
            return;
          case 1:
            title = "协会通知";
            break;
          case 2:
            title = "点赞通知";
            active = "点赞";
            break;
          case 3:
            title = "收藏通知";
            active = "收藏";
            break;
          case 4:
            title = "评论通知";
            if (commentType == 2) {
              active = "回复";
            } else {
              active = "评论";
            }
            break;
        }

        switch (commentType) {
          case 0:
            comment = "帖子";
            break;
          case 1:
            comment = "评论";
            break;
          case 2:
            comment = "回复";
            break;
          case 3:
            comment = "学习资料";
            break;
        }

        // 如果是单独处理点赞+收藏+评论的逻辑，应写在case外
        // 1： 处理点赞+收藏+评论的推送
        // 2： 处理点赞后所有在线的用户弹窗提醒
        // 这里需要根据具体需求编写代码
        let userName = nickname; // 假设已经获取到用户昵称
        message = `<b>${userName}</b>&nbsp;&nbsp;&nbsp;刚刚${active}了你的${comment}<br/><p style="font-size:12px;color:grep">${formattedDate}</p>`;
        this.openNotice(title, message);
      };

      // 监听错误
      webSocket.onerror = function (e) {
        // console.log("错误连接：", e);
      };

      // 监听关闭
      webSocket.onclose = function (e) {
        // console.log("关闭连接：", e);
      };
    },
  },
};
</script>

<style scoped>
.in-wrap {
  min-width: 500px;
}

body {
  margin: 0;
}

nuxt::-webkit-scrollbar {
  display: none;
}

.feedback {
  display: flex;
  padding: 0.52vw;
  border: 0.052vw solid lightgrey;
  box-shadow: 0.26vw 0.26vw 1.041vw #181818;
  border-radius: 6px;
  width: 2.083vw;
  height: 8.854vw;
  position: fixed;
  right: 0.3%;
  top: 30vh;
  z-index: 1111;
  background-color: #fff;
  flex-direction: column;
  justify-content: space-around;
  align-items: center
}

.callMe {
  width: 1.5625vw;
  font-size: 0.729vw;
}

.svg-icon {
  width: 1.5625vw;
  height: 1.5625vw;
  font-size: 1.7em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.one {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.two {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.form-vertical {
  margin: 0 4vw;
}

.form-vertical .el-form-item:nth-child(1) {
  display: flex;
  flex-direction: column;
  align-items: start;
  margin-left: 0;
}

.form-vertical .el-form-item:nth-child(1) .el-textarea {
  width: 357px;
}

.form-vertical .el-form-item .el-input {
  width: 296px;
}

.upload-demo {
  width: 800px;
}

.tel {
  margin-left: 100px;
}

.upload-demo {
  width: 375px;
}
</style>
